//
//  HMHomePictureView.swift
//  Weibo
//
//  Created by itteacher on 2017/7/28.
//  Copyright © 2017年 itteacher. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

//  每项的间距
private let ItemMargin: CGFloat = 5
//  每项的宽度
private let ItemWidth = (ScreenWidth - 2 * HomeCellMargin - 2 * ItemMargin) / 3

//  自定义首页配图
class HMHomePictureView: UICollectionView {

    //  数据源
    var picUrls: [HMHomePicture]? {
        didSet {
            messageLabel.text = "\(picUrls?.count ?? 0)"
            //  根据图片的个数计算大小，更新配图大小约束
            calcSize(count: picUrls!.count)
            //  数据源发生改变，重新加载数据
            self.reloadData()
        }
    }
    
    //  MARK: --    懒加载
    fileprivate lazy var messageLabel: UILabel = {
        let label = UILabel(fontSize: 20, textColor: UIColor.purple)
        return label
    }()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        //  设置大小
        flowLayout.itemSize = CGSize(width: ItemWidth, height: ItemWidth)
        //  设置行间距
        flowLayout.minimumLineSpacing = ItemMargin
        //  设置列间距
        flowLayout.minimumInteritemSpacing = ItemMargin
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  添加控件设置约束
    private func setupUI() {
        //  注册cell
        register(HMHomePictureViewCell.self, forCellWithReuseIdentifier: HomePictureViewCellIdentifier)
        //  设置数据源代理
        dataSource = self
        //  设置代理
        delegate = self
        
        addSubview(messageLabel)
        messageLabel.snp.makeConstraints { (make) in
            make.center.equalTo(self)
        }
    }
    
    //  根据配图的个数计算配图大小
    private func calcSize(count: Int) {
        
        //  判断是否是单张图片，使用单张图片作为配图的大小
        if count == 1 {
            //  图片的地址
            let imageUrl = picUrls!.first!.thumbnail_pic
            //  获取本地单张图片
            if let localImage = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: imageUrl) {
                //  获取本地图片的大小
                var imageSize = localImage.size
                //  图片过窄处理
                if localImage.size.width < 80 {
                    //  图片的宽度
                    let imageWidth: CGFloat = 80
                    //  图片的高度
                    var imageHeight = imageWidth / localImage.size.width * localImage.size.height
                    //  过长
                    if imageHeight > 150 {
                        //  修改图片的高度
                        imageHeight = 150
                    }
                    //  计算后的大小
                    imageSize = CGSize(width: imageWidth, height: imageHeight)
                }
                
                //  代码执行到此，说明单张图片一定存在，把图片的大小作为配图的大小去使用
                self.snp.updateConstraints({ (make) in
                    make.size.equalTo(imageSize).priority(.high)
                })
                
                //  把itemsize改成图片的大小
                let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
                flowLayout.itemSize = imageSize
                
                return
            }
        }
        
        
        //  计算列数
        let cols = count > 3 ? 3 : count
        //  计算行数
        let rows = (count - 1) / 3 + 1
        //  计算宽度
        let pictureViewWidth = CGFloat(cols) * ItemWidth + CGFloat(cols - 1) * ItemMargin
        //  计算高度
        let pictureViewHeight = CGFloat(rows) * ItemWidth + CGFloat(rows - 1) * ItemMargin
        
        //  更新配图大小
        self.snp.updateConstraints { (make) in
            //  提示： 更新约束的时候，如果约束有优先级那么需要在更新的时候也要设置约束优先级
            make.size.equalTo(CGSize(width: pictureViewWidth, height: pictureViewHeight)).priority(.high)
        }
        
        //  把itemsize改成图片的大小
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSize(width: ItemWidth, height: ItemWidth)
    }

}


//  MARK: --实现UICollectionViewDataSource
extension HMHomePictureView: UICollectionViewDataSource, UICollectionViewDelegate,SDPhotoBrowserDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomePictureViewCellIdentifier, for: indexPath) as! HMHomePictureViewCell
        //  设置图片模型
        cell.homePic = picUrls![indexPath.item]
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = picUrls!.count
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
        
    }
    
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        
        let urlStr = picUrls![index].thumbnail_pic!.replacingOccurrences(of: "thumbnail", with: "bmiddle")
        return URL(string: urlStr)

    }
    
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        
        let cell = self.cellForItem(at: IndexPath(item: index, section: 0)) as! HMHomePictureViewCell
        return cell.imageView.image
    }

}

//  自定义首页配图cell
class HMHomePictureViewCell: UICollectionViewCell {
    //  MARK: --   懒加载控件
    fileprivate lazy var imageView: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        //  按照图片原始比例等比显示
        imageView.contentMode = .scaleAspectFill
        //  裁剪超出部分
        imageView.clipsToBounds = true
        return imageView
    }()
    
    //  gif图片
    fileprivate lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
    //  模型数据
    var homePic: HMHomePicture? {
        didSet {
            
            if let urlStr = homePic?.thumbnail_pic {
                imageView.sd_setImage(with: URL(string: urlStr), placeholderImage: UIImage(named: "timeline_image_placeholder"))
                print(urlStr)
                if urlStr.hasSuffix(".gif") {
                    //  gif图片显示
                    gifImageView.isHidden = false
                } else {
                    //  不是gif隐藏icon
                    gifImageView.isHidden = true
                }
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  添加控件设置约束
    fileprivate func setupUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(gifImageView)
        imageView.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        gifImageView.snp.makeConstraints { (make) in
            make.bottom.trailing.equalTo(contentView)
        }
    }
    
}



